<template>
	<view class="content" style="background-color: #F4F4F4;height: 100vh;">
		<tn-nav-bar bgClass="bg-gradual-blue" :isBack="isBack">
			<view>
				{{ bleName }}
			</view>
		</tn-nav-bar>
		<view :style="{paddingTop: vuex_custom_bar_height + 'px'}">
			<view class='tn-flex tn-flex-wrap tn-margin-top-sm' style="height: 60rpx;">
				<view class="tn-flex tn-flex-basic-lg padding-left " style="height: 100%;border-radius: 12rpx;">
					<tn-list-cell padding="6" height='100%' style="width: 100%;height: 100%;border-radius: 6px;"
						v-if="showTime">
						<view class="list-icon-text">
							<view class="list__left" @click="JiaoFei">
								<view class="list__left__text">到期剩余时间：{{leftDays}} 天</view>
							</view>
							<view class="list__right">
								<text class="tn-icon-close" @click="showTime = false"></text>
							</view>
						</view>
					</tn-list-cell>
					<tn-list-cell padding="6" height='100%' style="width: 100%;height: 100%;border-radius: 12rpx;"
						v-else>
						<view class="list-icon-text">
							<view class="list__left" @click="JiaoFei">
								<view class="list__left__text">到期日期：{{leftDays}}</view>
							</view>
						</view>
					</tn-list-cell>
				</view>
				<view class="tn-flex ">
					<tn-button class="tn-margin-left-xs" :fontSize="30" height="60rpx" @click="refreshData">
						<text class="tn-icon-refresh"></text>
					</tn-button>
					<tn-button class="tn-margin-left-xs" :fontSize="30" height="60rpx" @click="toScan">
						<text class="tn-icon-scan"></text>
					</tn-button>
					<tn-button class="tn-margin-left-xs" :fontSize="30" height="60rpx" @click="showBtn">
						<text class="tn-icon-edit"></text>
					</tn-button>
				</view>

			</view>


			<view class="tn-margin">
				<text class="tn-color-gray tn-margin-right-sm tn-text-lg"> 型号</text>
				<text class="tn-text-xl tn-text-bold">{{State.BMSCode?State.BMSCode:''}}</text>
			</view>


			<view class="margin-top-lg">
				<tn-grid col="2" align="center">
					<tn-grid-item backgroundColor='#F4F4F4'>
						<view class="task-item b-card ">
							<view class="b-flex-space">
								<view class="task-item-describe">
									<view class="title b-fontw">
										电压
									</view>
									<view class="text">
										{{macid? State.BetteryV_All :'' }}
										<text class="text-lg" style="padding-left: 6rpx;">V</text>
									</view>
								</view>
								<image class="task-item-icon" src="/static/img/ble/dy.png" mode="">
								</image>
							</view>
						</view>
					</tn-grid-item>
					<tn-grid-item backgroundColor='#F4F4F4'>
						<view class="task-item b-card ">
							<view class="b-flex-space">
								<view class="task-item-describe">
									<view class="title b-fontw">
										保护板温度
									</view>
									<view class="text">
										{{macid? State.TC_T : ''}}
										<text class="text-lg" style="padding-left: 6rpx;">°C</text>
									</view>
								</view>
								<image class="task-item-icon" src="/static/img/ble/wd.png" mode="">
								</image>
							</view>
						</view>
					</tn-grid-item>
					<tn-grid-item backgroundColor='#F4F4F4'>
						<view class="task-item b-card ">
							<view class="b-flex-space">
								<view class="task-item-describe">
									<view class="title b-fontw">
										充电电流
									</view>
									<view class="text">
										{{macid? State.CPowerA : ''}}
										<text class="text-lg" style="padding-left: 6rpx;"> A</text>
									</view>
								</view>
								<image class="task-item-icon" src="/static/img/ble/dl.png" mode="">
								</image>
							</view>
						</view>
					</tn-grid-item>
					<tn-grid-item backgroundColor='#F4F4F4'>
						<view class="task-item b-card ">
							<view class="b-flex-space">
								<view class="task-item-describe">
									<view class="title b-fontw">
										放电电流
									</view>
									<view class="text">
										{{macid? State.DPowerA : ''}}
										<text class="text-lg" style="padding-left: 6rpx;"> A</text>
									</view>
								</view>
								<image class="task-item-icon" src="/static/img/ble/dl.png" mode="">
								</image>
							</view>
						</view>
					</tn-grid-item>
				</tn-grid>
			</view>




			<view class="tn-flex tn-flex-wrap tn-margin tn-border-solid-top">
				<view class="tn-flex-basic-md tn-margin-top-sm tn-border-solid-right">
					<view class="tn-flex tn-flex-center" style="line-height: 30px;">
						<text class="tn-flex-center tn-text-right tn-color-gray" style="width: 65px;">电池状态</text>
						<view class="tn-margin-left-sm">
							<tn-tag class="tn-text-bold" v-if="State.WorkStatus*1===0">
								<tn-badge backgroundColor="#ff0000" :dot="true" :radius="15" margin="10rpx 10rpx" />
								放电中
							</tn-tag>
							<tn-tag class="tn-text-bold" v-if="State.WorkStatus*1===1">
								<tn-badge backgroundColor="#0000ff" :dot="true" :radius="15" margin="10rpx 10rpx" />
								充电中
							</tn-tag>
							<tn-tag class="tn-text-bold" v-if="State.WorkStatus*1===2">
								<tn-badge backgroundColor="#55ff7f" :dot="true" :radius="15" margin="10rpx 10rpx" />
								闲置
							</tn-tag>
						</view>
					</view>
					<view class="tn-flex tn-flex-center" style="line-height: 30px;">
						<text class="tn-flex-center tn-text-right tn-color-gray" style="width: 65px;">充电MOS</text>
						<view class="tn-margin-left-sm">
							<tn-tag class="tn-text-bold" v-if="Seting.CHON*1===0">
								<tn-badge backgroundColor="#ff0000" :dot="true" :radius="15"
									margin="10rpx 10rpx"></tn-badge>
								关闭</tn-tag>
							<tn-tag class="tn-text-bold" v-if="Seting.CHON*1===1">
								<tn-badge backgroundColor="#55ff7f" :dot="true" :radius="15"
									margin="10rpx 10rpx"></tn-badge>
								开启</tn-tag>
						</view>
					</view>
					<view class="tn-flex tn-flex-center" style="line-height: 30px;">
						<text class="tn-flex-center tn-text-right tn-color-gray" style="width: 65px;">放电MOS</text>
						<view class="tn-margin-left-sm">
							<tn-tag class="tn-text-bold" v-if="Seting.DHON*1===0">
								<tn-badge backgroundColor="#ff0000" :dot="true" :radius="15"
									margin="10rpx 10rpx"></tn-badge>
								关闭</tn-tag>
							<tn-tag class="tn-text-bold" v-if="Seting.DHON*1===1">
								<tn-badge backgroundColor="#55ff7f" :dot="true" :radius="15"
									margin="10rpx 10rpx"></tn-badge>
								开启</tn-tag>
						</view>
					</view>
					<view class="tn-flex tn-flex-center" style="line-height: 30px;">
						<text class="tn-flex-center tn-text-right tn-color-gray" style="width: 65px;">均衡状态</text>
						<view class="tn-margin-left-sm">
							<tn-tag class="tn-text-bold" v-if="Seting.EMST*1===0">
								<tn-badge backgroundColor="#ff0000" :dot="true" :radius="15"
									margin="10rpx 10rpx"></tn-badge>
								关闭</tn-tag>
							<tn-tag class="tn-text-bold" v-if="Seting.EMST*1===1">
								<tn-badge backgroundColor="#55ff7f" :dot="true" :radius="15"
									margin="10rpx 10rpx"></tn-badge>
								开启</tn-tag>
						</view>
					</view>
				</view>
				<view class="tn-flex-basic-md">
					<view class="tn-flex">
						<view class="tn-flex-basic-md">
							<view class="tn-margin-top-sm tn-margin-left-sm">
								<view class="tn-color-bluepurple tn-text-xxl tn-text-bold">
									{{State.FCC?State.FCC:0}}<text class="tn-text-lg">AH</text>
								</view>
								<view class="tn-color-gray tn-text-md">
									总容量
								</view>
								<view class="tn-color-orangered tn-text-xxl tn-margin-top-lg tn-text-bold" v-if="macid">
									{{State.BetteryType*1===0?'三元':'铁锂'}}
								</view>
								<view class="tn-color-orangered tn-text-xxl tn-margin-top-lg tn-text-bold" v-else>
									未知
								</view>
								<view class="tn-color-gray tn-text-md">
									电池类型
								</view>
							</view>
						</view>
						<view class=" tn-flex tn-flex-basic-md" v-if="State.FCC">
							<view class=" tn-flex-end tn-flex-col-bottom">
								<qiun-data-charts width="100" height="80" canvasId="qweasd" type="arcbar" :opts="opts"
									:chartData="chartData" :canvas2d="true" />
							</view>
						</view>
					</view>

				</view>
			</view>

			<view class="tn-margin-sm">
				<tn-list-view title="电芯电压" unlined="bottom">
					<tn-grid col="4" align="between" v-if="macid">
						<tn-grid-item v-for="(item,index) in VoltageArry" :key="index" style="padding: 2px;">
							<view style="width: 100%;display: flex; justify-content: center;">
								<view
									:class='item*1===State.CeilingVoltage*1?"bg-img-dc-max":item*1===State.MinimumVoltage*1?"bg-img-dc-min":"bg-img-dc"'>
									<view
										style="display: flex; justify-content: space-around;align-items: center;flex-direction: column;width: 100%;height: 100%;padding: 5px;">
										<view class="text-bold">{{item}}mV</view>
										<view class="text-sm">电芯 {{index+1}}</view>
									</view>
								</view>
							</view>
						</tn-grid-item>
					</tn-grid>
				</tn-list-view>
			</view>

		</view>










		<view style="height: 6vh;"></view>



		<!-- 模态框 -->
		<tn-modal v-model="show" width="84%" :radius="12" title="输入设备编码连接" custom :button="[
          {
            text: '确定',
            backgroundColor: 'tn-bg-indigo',
            fontColor: '#FFFFFF'
          }
        ]" showCloseBtn :maskCloseable="false" zoom @click="clickBtn">
			<view class="custom-modal-content">
				<tn-form :labelWidth="140" class="tn-margin">
					<tn-form-item label="设备编码" :borderBottom="false">
						<tn-input v-model="num" placeholder="请输入设备编码"></tn-input>
						<view slot="right" class="tn-flex tn-flex-col-center tn-flex-row-center">
							<tn-button :fontSize="30" height="46rpx" @click="toScan">
								<text class="tn-icon-scan"></text>
							</tn-button>
						</view>
					</tn-form-item>
				</tn-form>
			</view>
		</tn-modal>


		<!-- 模态框 -->
		<tn-modal v-model="feiShow" width="84%" :radius="12" custom :button="[
          {
            text: '确定',
            backgroundColor: 'tn-bg-indigo',
            fontColor: '#FFFFFF'
          }
        ]" showCloseBtn :maskCloseable="false" zoom @click="btnPay" @cancel='toClose'>
			<view class="custom-modal-content">
				<template v-if="!showpayImg">
					<view class="text-bold text-lg">选择续费套餐</view>
					<view class="tn-margin">
						<tn-radio-group shape="square" wrap v-model="payVal">
							<tn-radio :name="payList['oneYear']">一年（{{payList['oneYear']}}币）</tn-radio>
							<tn-radio :name="payList['twoYear']">二年（{{payList['twoYear']}}币）</tn-radio>
							<tn-radio :name="payList['threeYear']">三年（{{payList['threeYear']}}币）</tn-radio>
							<tn-radio :name="payList['fourYear']">四年（{{payList['fourYear']}}币）</tn-radio>
							<tn-radio :name="payList['fiveYear']">五年（{{payList['fiveYear']}}币）</tn-radio>
						</tn-radio-group>
					</view>
				</template>
				<template v-else>
					<view class="text-bold text-lg">使用微信扫码付款</view>
					<image :src="'data:image/png;base64,'+payImg" style="width: 300px;height: 300px;"></image>
				</template>
			</view>
		</tn-modal>

	</view>
</template>

<script>
	import store from '@/store/index.js'
	import {
		getDateFunc,
		getDeviceInfo,
		getPayList,
		getImgData
	} from '@/api/modules/mingtang';
	export default {
		data() {
			return {
				feiShow: false,
				showpayImg: false,
				showTime: false,
				leftDays: '',
				show: false,
				isBack: true,
				bleName: '',
				num: '',
				mds: null, //登录token
				macid: null, //电池设备ID
				Seting: null,
				State: null,
				VoltageArry: [],
				chartData: {},
				deviceInfo: {},
				payList: {},
				payImg: null,
				payVal: null,
				opts: {
					color: ["#1890FF"],
					padding: undefined,
					title: {
						name: "80%",
						fontSize: 18,
						color: "#2fc25b"
					},
					subtitle: {
						name: "SOC",
						fontSize: 12,
						color: "#000"
					},
					extra: {
						arcbar: {
							type: "default",
							width: 12,
							backgroundColor: "#E9E9E9",
							startAngle: 0.75,
							endAngle: 0.25,
							gap: 2,
							linearType: "custom"
						}
					},
				}
			}
		},
		onLoad(query) {
			this.show = true
			getPayList().then(res => {
				if (res.code === 200) {
					this.payList = res.data;
				}
			})
			if(query.id){
				this.loadData(query.id)
			}
		},
		methods: {
			refreshData() {
				if (this.macid) {
					this.loadData(this.macid)
				}
			},
			loadData(macid) {
				getDateFunc(macid).then(res => {
					this.show = false
					if (res.code === 200) {
						store.commit('$tStore', {
							name: 'vuex_ble_id',
							value: macid
						})

						store.commit('$tStore', {
							name: 'vuex_ble_name',
							value: macid
						})

						this.macid = macid
						this.bleName = macid
						this.Seting = JSON.parse(res.data.Seting)
						this.State = JSON.parse(res.data.State)
						for (var i = 0; i < this.State.BetteryC * 1; i++) {
							this.VoltageArry[i] = this.State['BetteryV_' + (i + 1)]
						}
						this.getServerData();
						this.$forceUpdate()
					} else {
						this.macid = null
						this.$tn.message.toast('设备不存在')
					}
				}).then(res => {
					getDeviceInfo(macid).then(data => {
						console.log('data', data);
						if (data.code === 200) {
							this.deviceInfo = data.data
							let leftDays = checkTime(this.deviceInfo.expire)
							if (leftDays <= 60) {
								this.showTime = true
								this.leftDays = leftDays
							} else {
								this.leftDays = this.deviceInfo.expire ? toDate(this.deviceInfo.expire *
									1000, 'yyyy-MM-dd') : ''
							}
						}
					})
				})
			},
			clickBtn(event) {
				this.show = false
				if (this.num === '' || this.num.length < 1) {
					return
				}
				this.loadData(this.num)
			},
			toScan() {
				uni.scanCode({
					success: (res) => {
						console.log('条码类型：' + res.scanType);
						console.log('条码内容：' + res.result);
						this.loadData(res.result)
					}
				})
			},
			showBtn() {
				this.show = true
			},
			JiaoFei() {
				this.feiShow = true
			},
			toClose() {
				this.showpayImg = false
				this.feiShow = false
			},
			btnPay() {
				if (!this.macid) {
					this.$tn.message.toast('请先连接设备')
					return
				}
				if (!this.showpayImg) {
					for (let key in this.payList) {
						let yearType = key
						let money = this.payList[key]
						if (money * 1 === this.payVal * 1) {
							let ids = this.deviceInfo.id + ';'
							getImgData(ids, yearType, money).then(res => {
								this.payImg = res.data.img
								this.showpayImg = true
							})
							break;
						}
					}
				} else {
					this.showpayImg = false
					this.feiShow = false
				}

			},
			getServerData() {
				//模拟从服务器获取数据时的延时
				setTimeout(() => {
					this.opts.title.name = this.State.SOC + '%'
					let res = {
						series: [{
							name: "SOC",
							data: (this.State.SOC / 100)
						}]
					};
					this.chartData = JSON.parse(JSON.stringify(res));
				}, 500);
			},
		}
	}


	function toDate(v, format) {
		format = format ? format : "yyyy-MM-dd HH:mm:ss"
		if (!v) return "";
		var d = v;
		if (typeof v === 'string') {
			if (v.indexOf("/Date(") > -1)
				d = new Date(parseInt(v.replace("/Date(", "").replace(")/", ""), 10));
			else
				d = new Date(Date.parse(v.replace(/-/g, "/").replace("T", " ").split(".")[0]));
		} else {
			d = new Date(v)
		}
		var o = {
			"M+": d.getMonth() + 1,
			"d+": d.getDate(),
			"h+": d.getHours(),
			"H+": d.getHours(),
			"m+": d.getMinutes(),
			"s+": d.getSeconds(),
			"q+": Math.floor((d.getMonth() + 3) / 3),
			"S": d.getMilliseconds()
		};
		if (/(y+)/.test(format)) {
			format = format.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length));
		}
		for (var k in o) {
			if (new RegExp("(" + k + ")").test(format)) {
				format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" +
						o[k])
					.length));
			}
		}
		return format;
	}


	function checkTime(expire) {
		let gqStr = toDate(expire * 1000)
		console.log('gqStr', gqStr);
		const date1 = new Date(expire * 1000);
		const date2 = new Date();
		// 将时间转换为毫秒
		const diffTime = Math.abs(date1.getTime() - date2.getTime());
		// 计算天数差
		const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
		console.log('diffDays', diffDays);
		return diffDays;
	}
</script>

<style scoped lang="scss">
	.radius-25 {
		border-radius: 25rpx;
	}

	.b-card {
		margin: 26rpx 32rpx;
		padding: 25rpx;
		background-color: #FFFFFF;
		border-radius: 18rpx;
		box-shadow: 12rpx 12rpx 10rpx #a7a7a7;
	}

	.b-flex-space {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.b-fontw {
		font-weight: 600;
	}


	.task-item {

		.task-item-icon {
			width: 80rpx;
			height: 80rpx;
		}

		.task-item-describe {
			height: 100rpx;
			width: 150rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			margin-right: 30rpx;

			.title {
				font-size: 24rpx;
			}

			.text {
				margin-top: 20rpx;
				font-size: 46rpx;
			}
		}
	}

	.bg-img-dc-max {
		background-image: url('/static/img/ble/dx-max.png');
		background-size: 100% 100%;
		color: #13227a;
		height: 90rpx;
		width: 86px;
	}

	.bg-img-dc-min {
		background-image: url('/static/img/ble/dx-min.png');
		background-size: 100% 100%;
		height: 90rpx;
		color: #0b988f;
		width: 86px;
	}

	.bg-img-dc {
		background-image: url('/static/img/ble/dx.png');
		background-size: 100% 100%;
		height: 90rpx;
		width: 86px;
		color: #1296db;
	}

	.empty {
		&__item {
			background-color: #FFFFFF;
			padding: 20rpx 0;
		}
	}


	.list-icon-text,
	.list-image-text {
		display: flex;
		height: 100%;
		align-items: center;
		justify-content: space-between;
	}

	.list-image-text {
		.list {
			&__left {
				&__image {
					width: 20rpx;
					height: 20rpx;
				}
			}
		}
	}
</style>